package com.top10.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * Created by zwp on 2018/5/1.
 */

public class WXUtil {


    public static void main(String[] args) throws Exception{
        //System.out.println(getJsapiTicket(getAccess_token("wx4adbfb50b90ed032","ad773f67dedfd7aab543da1d8fa3dc48")));
     //   System.out.println(getOutTradeNo());
    }

    /**
     * 两个小时的过期 JsapiTicket
     * @param AccessToken
     * @return
     * @throws Exception
     */
    public static String getJsapiTicket(String AccessToken)throws Exception{
        HttpClient httpclient =  HttpClients.createDefault();
        String smsUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + AccessToken + "&type=jsapi";
        HttpGet httpGet = new HttpGet(smsUrl);
        String strResult = "";

        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
                    /*读返回数据*/
            strResult = EntityUtils.toString(response
                    .getEntity());
        }
        Map resultMap = (Map) JSON.parse(strResult);
        return (String)resultMap.get("ticket");
    }
    /**
     * 两个小时的过期 ACCESSTOKEN
     * @param appid
     * @param secret
     * @return
     * @throws Exception
     */
    public static String getAccess_token(String  appid, String secret) throws Exception{
        HttpClient httpclient =  HttpClients.createDefault();
        String smsUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&SECRET=" + secret;
        HttpGet httpGet = new HttpGet(smsUrl);
        String strResult = "";

        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
                    /*读返回数据*/
            strResult = EntityUtils.toString(response
                    .getEntity());
        }
        Map resultMap = (Map) JSON.parse(strResult);
        String AccessToken = (String)resultMap.get("access_token");
        System.out.println(AccessToken);
        return AccessToken;
    }

    /**
     *生成18位随机订单号
     * 时间+5位随机数
     *
     */
    public static String getOutTradeNo(){
        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        String time=format.format(date);
        String radom = String.valueOf(new Random(7).nextInt(10000));
        String outTradeNo = time + radom ;
        return outTradeNo;
    }

    /**
     *生成当前时间戳（秒）
     *
     * @return
     */
    public static int getSecondTimestamp(){
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime()/1000);
        return Integer.valueOf(timestamp);
    }



    /**
     * 获取Openid
     * @param appid
     * @param secret
     * @param code
     * @return
     * @throws Exception
     */
    public static Map<String,String> getLoginAccessToken(String  appid, String secret, String code) throws Exception{
    //    HttpClient httpclient =  HttpClients.createDefault();
        String smsUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ appid +"&SECRET="+ secret + "&code=" + code + "&grant_type=authorization_code";
/*        HttpGet httpGet = new HttpGet(smsUrl);
        String strResult = "";

        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
                    *//*读返回数据*//*
            strResult = EntityUtils.toString(response
                    .getEntity(),"UTF-8");
        }*/

      //  System.out.println(strResult);
        Map resultMap = (Map) JSON.parse( HttpClientUtil.get(smsUrl));
        return resultMap;
    }

    public static Map<String,String> getUserInfo(String loginAccessToken, String openId) throws Exception{
        HttpClient httpclient =  HttpClients.createDefault();
        String smsUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+ loginAccessToken +"&openid="+ openId + "&lang=zh_CN=";
        HttpGet httpGet = new HttpGet(smsUrl);
        String strResult = "";

        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            /*读返回数据*/
            strResult = EntityUtils.toString(response
                    .getEntity(),"UTF-8");
        }
        Map resultMap = (Map) JSON.parse(strResult);
        return resultMap;
    }


    /**
     * 获取关注该公众号的全部OpenId
     * @return
     * @throws Exception
     */

//    public static List<String> getAllUserOpenId() throws Exception{
//        HttpClient httpclient =  HttpClients.createDefault();
//        String smsUrl="https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + WXConst.ACCESSTOKEN;
//        HttpGet httpGet = new HttpGet(smsUrl);
//        String strResult = "";
//
//        HttpResponse response = httpclient.execute(httpGet);
//        if (response.getStatusLine().getStatusCode() == 200) {
//                    /*读返回数据*/
//            strResult = EntityUtils.toString(response
//                    .getEntity());
//        }
//       // System.out.println(strResult);
//        Map resultMap = (Map) JSON.parse(strResult);
//        Map<String, Object> openidMap = (Map<String, Object>) resultMap.get("data");
//        List<String> openIdList = (List<String>) openidMap.get("openid");
//        return openIdList;
//    }
//
//
//    public static boolean deleteFile(String fileName) {
//        File file = new File(fileName);
//        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
//        if (file.exists() && file.isFile()) {
//            if (file.delete()) {
//                //System.out.println("删除单个文件" + fileName + "成功！");
//                return true;
//            } else {
//                //System.out.println("删除单个文件" + fileName + "失败！");
//                return false;
//            }
//        } else {
//            //System.out.println("删除单个文件失败：" + fileName + "不存在！");
//            return false;
//        }
//    }
//
//
//
//    public static boolean isEnableType(String fileName, String type){
//
//        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
//        boolean enableType = false;
//        if("image".equals(type)){
//            for (int i = 0; i < WXConst.img.length; i++) {
//                if (WXConst.img[i].equals(fileType)) {
//                    enableType = true;
//                }
//            }
//        }
//
//        if("video".equals(type)){
//            for (int i = 0; i < WXConst.video.length; i++) {
//                if (WXConst.video[i].equals(fileType)) {
//                    enableType = true;
//                }
//            }
//        }
//
//        if("voice".equals(type)){
//            for (int i = 0; i < WXConst.music.length; i++) {
//                if (WXConst.music[i].equals(fileType)) {
//                    enableType = true;
//                }
//            }
//        }
//        if("thumb".equals(type)){
//            for (int i = 0; i < WXConst.thumb.length; i++) {
//                if (WXConst.thumb[i].equals(fileType)) {
//                    enableType = true;
//                }
//            }
//        }
//        if(enableType == false){
//            return false;
//        }
//
//        return true;
//    }


}
